﻿using BlogDemo.Common;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BlogDemo.Infrastructure
{
    internal static class ChangeTrackerExtensions
    {
        /// <summary>
        /// 设置影子属性
        /// </summary>
        /// <param name="changeTracker"></param>
        public static void SetShadowISoftDeletableProperties(this ChangeTracker changeTracker)
        {
            changeTracker.DetectChanges(); 
            var t = changeTracker.Entries().
                Where(entryEntity => typeof(ISoftDleteEntity).IsAssignableFrom(entryEntity.Entity.GetType()));

            foreach (var entry in t)
            {
                if (typeof(ISoftDleteEntity).IsAssignableFrom(entry.Entity.GetType()))
                {
                    if (entry.State == EntityState.Deleted)
                    {
                        entry.State = EntityState.Modified;
                        entry.Property("IsDeleted").CurrentValue = true;
                    }
                    else if (entry.State == EntityState.Added)
                    {
                        entry.Property("IsDeleted").CurrentValue = false;
                    }
                    else
                    {
                        entry.Property("IsDeleted").CurrentValue = entry.Property("IsDeleted").OriginalValue;
                    }
                }
            }
        }

    }
}
